#include <stdio.h>
#include <cjson/cJSON.h>
#include <stdlib.h>
#define cfgfile "conf_s.json"

int main()
{
    cJSON *root = NULL;

    FILE *file = NULL;
    char *data = NULL;
    long len = 0;

    // open config file
    if (cfgfile == NULL || (file = fopen(cfgfile, "rb")) == NULL)
    {
        printf("open file fail! %s", cfgfile);
        return -1;
    }

    // get file len
    if (fseek(file, 0, SEEK_END) != 0 || (len = ftell(file)) == 0 ||
        fseek(file, 0, SEEK_SET) != 0)
    {
        printf("cfgfile len error!len:%ld", len);
        fclose(file);
        return -1;
    }

    if ((data = (char *)malloc(len + 1)) == NULL ||
        fread(data, 1, len, file) != len)
    {
        printf("read data fail!");
        fclose(file);
        return -1;
    };

    // close file
    fclose(file);

    // json parse
    root = cJSON_Parse(data);
    if (root == NULL)
    {
        free(data);
        printf("cJSON_Parse fail![%s]\n", cJSON_GetErrorPtr());
        return -1;
    }

    cJSON *name_json = cJSON_GetObjectItem(root, "name");
    if (name_json != NULL)
    {
        char *name = cJSON_Print(name_json); //将JSON结构体打印到字符串中 需要自己释放
        printf("name:%s\n", name);
        free(name);
    }

    cJSON *type_json = cJSON_GetObjectItem(root, "type");
    if (type_json != NULL)
    {
        char *type = cJSON_Print(type_json); //将JSON结构体打印到字符串中 需要自己释放
        printf("type:%s\n", type);
        free(type);
    }

    cJSON_Delete(root);
    free(data);

    return 0;
}